package com.csw.compose.ui

import android.os.Bundle
import androidx.navigation.NavHostController
import androidx.navigation.navArgument
import com.csw.compose.ui.Destination.Companion.DATA_KEY
import com.google.gson.Gson
import com.google.gson.GsonBuilder

val GSON: Gson = GsonBuilder().serializeNulls().create()
/**
 * 解析数据对象
 */
inline fun <reified T> Bundle.getDataObject(): T? {
    val dataString = getString(DATA_KEY) ?: return null
    return try {
        GSON.fromJson(dataString, T::class.java)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

/**
 * 页面路由组件
 * @param path 页面路径
 *
 * class ExampleData(val p1: String, val p2: String) {
 *    companion object : Destination("Example")
 * }
 */
open class Destination(private val path: String) {

    companion object {
        /** 参数key */
        const val DATA_KEY = "data"

        /**
         * 数据参数
         *
         * Navigation的传参过于麻烦，这里所有页面参数以json字符串的方式传值
         */
        val DATA_ARGUMENT = navArgument(DATA_KEY) {}
    }

    /** 路由路径 */
    val route = "${path}?${DATA_ARGUMENT.name}={${DATA_ARGUMENT.name}}"

    /**
     * 获取带参数的链接，通过[NavHostController.navigate]跳转页面
     * @param data 若页面有跳转参数可以传入
     */
    fun getRouteWithParams(data: Any? = null): String {
        data ?: return path
        return "${path}?${DATA_ARGUMENT.name}=${GSON.toJson(data)}"
    }
}


